/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.doc.sender.ui;

import com.database.entity.Menus;
import com.database.entity.UserLogs;
import database.senderUtil;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import javax.swing.*;
import javax.swing.JPopupMenu.Separator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author parent
 */
public class mainFrame extends JFrame {
    private JMenuBar menubar;
    private int UserID;
    private JDesktopPane desktop;
    PageFormat pformat = PrinterJob.getPrinterJob().defaultPage();
    public int getGroupID() {
        return GroupID;
    }

    public void setGroupID(int GroupID) {
        this.GroupID = GroupID;
    }

    public int getJobID() {
        return JobID;
    }

    public void setJobID(int JobID) {
        this.JobID = JobID;
    }

    public int getUserID() {
        return UserID;
    }

    public void setUserID(int UserID) {
        this.UserID = UserID;
    }
    private int GroupID;
    private int JobID;
    
    class MyMenu extends JMenuItem {
        int MenuID;
        String Description;
        public int getMenuID() {
            return MenuID;
        }

        public void setMenuID(int MenuID) {
            this.MenuID = MenuID;
        }
        public MyMenu(int ID,String text,String ToolTips) {
            super(text);
            //super(text,ToolTips);
            this.setToolTipText(ToolTips);
            this.MenuID=ID;
        }
        
    }
    public void logOut(){
        try {
       
       
        InetAddress ownIP=InetAddress.getLocalHost();
        Session session = senderUtil.getSessionFactory().getCurrentSession();
        String queryString = "from UserLogs where login_status ='1'  and ip_address=:ip";
        Query query = session.createQuery(queryString);  
        query.setString("ip", ownIP.getHostAddress());
        Object queryResult = query.uniqueResult(); 
        UserLogs userlog=(UserLogs)queryResult;
        if (userlog!=null){
        userlog.setLoginStatus("0");
        session.update(userlog);
        System.out.println("Update Session ...");
        } else {
          System.out.println("User tidak ada");          
        }
        
        session.getTransaction().commit(); 
        } catch (Exception ex){
//            ex.printStackTrace(); 
            System.out.println(ex.getMessage());
        }
    }
    private void drawMenuModel(int groupid){
       Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            menubar=new JMenuBar();  
            transaction = session.beginTransaction();
//            String queryString = "select menu from MenuPrivs privs "+
//            "inner join privs.userGroups as groups,privs.Menus as menu"+
//            " where groups.id=:group "
//            + " order by menu.pid asc,menu.id asc";
            String queryString="from Menus order by pid,id";       
            Query query = session.createQuery(queryString);
//            query.setInteger("group",groupid);
            
            List listRecord=query.list();
            JMenu[] parents=new JMenu[6];
            MyMenu[] child=new MyMenu[22];
//            JMenuItem[] child=new JMenuItem[22];
            int iter=0;
            if (listRecord!=null){
                    for (Object o:listRecord){
//                        MenuPrivs ds=(MenuPrivs)o;
                        Menus menu=(Menus)o;//ds.getMenus();
                        if (menu.getPid()==0){
                           parents[iter+1]=new JMenu(menu.getCaption());
//                           parents[iter+1].addMenuListener(this);
                           iter++;
//                           System.out.println(iter+":"+ds.getCaption());
                        } else {
                            int pid=menu.getPid();
                            int clid=menu.getId();
                            child[clid]=new MyMenu(menu.getId() ,
                                    menu.getCaption(),menu.getDescription());
                           // child[clid]=new JMenuItem(ds.getCaption());
                            if (menu.getCaption().equals("-")){
                               child[clid-1].add(new Separator()); 
                            } else {
                                parents[pid].add(child[clid]);
                                Action LeftAction=new LeftAction(menu.getCaption(),
                                        null,menu.getDescription(),0);
                                child[clid].setAction(LeftAction);
                                //child[clid].setEnabled(ds.getGrantRead().equals("1"));
                            }
                            
//                          System.out.println(ds.getId()+":"+pid+":"+ds.getCaption());
                        }
                        
                    }
                  for (int i=1;i<parents.length;i++) {
                      menubar.add(parents[i]);
                  }
                }
            transaction.commit();
            session.close();    
             
        } catch (Exception e){
            //return false;
            e.printStackTrace();
            System.out.println(e.getMessage());
           
        }
   } 
    class LeftAction extends AbstractAction {
    public LeftAction(String text, ImageIcon icon,
                      String desc, Integer Tag) {
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue("TAG",Tag);
       // putValue(MNEMONIC_KEY, mnemonic);
    }
    public void actionPerformed(ActionEvent e) {
       // System.out.println("Action for first button/menu item :"+e.getSource().toString());
        MyMenu menus=(MyMenu)e.getSource();
        ExecuteMenu(menus.getMenuID(),menus.getToolTipText());
//        System.out.println(menus.getMenuID());
    }

        
    }
    public void showPendingDocument(){
        DocumentPendingFrame pending=new DocumentPendingFrame();
        pending.setUserId(UserID);
        pending.setGroupId(GroupID);
        pending.setJobId(JobID);
        pending.setVisible(true);
    }
    
    
    public void doPageSetup() {
        PrinterJob pjob = PrinterJob.getPrinterJob();
        pformat = pjob.pageDialog(pformat);
    }
    private void ExecuteMenu(int menuID,String Desc) {
            //throw new UnsupportedOperationException("Not yet implemented");
            switch(menuID){
                case 6:
                    LoginFrame login= new LoginFrame();
                    login.setVisible(true);
                    break;
                case 7:
                    //showLogout Process
                    logOut();
                    break;
                case 8:
                    PrinterJob pj=PrinterJob.getPrinterJob();
                    pj.printDialog();
                    break;
                case 9:
                    doPageSetup();
                    break;
                case 10:
                    System.exit(0);
                    break;
                case 11:
                    DocSourceFrame sourceframe=new DocSourceFrame();
//                    desktop.add(sourceframe);
                    sourceframe.setVisible(true);
                    break;
                case 12:
                    ListPDFDocumentFrame inbox=new ListPDFDocumentFrame();
//                    desktop.add(inbox);
                    inbox.setVisible(true);
                    break;
                case 13:
                    ListGroupFrame grouplist=new ListGroupFrame();
//                    desktop.add(grouplist);
                    grouplist.setVisible(true);
                    break;
                case 14:
                    ListUserFrame userlist=new ListUserFrame();
//                    desktop.add(userlist);
                    userlist.setVisible(true);
                    break;
               
                
                case 15://Hak akses
                    PrivilegeFrame akses=new PrivilegeFrame();
//                    desktop.add(akses);
                    akses.setVisible(true);
                    break;
                case 16:
                    PDFViewerFrame viewerframe=new PDFViewerFrame(true);
                    viewerframe.setVisible(true);
                    viewerframe.doOpen();
                    break;
                case 17:
                    ListPDFDocumentFrame listpdf=new ListPDFDocumentFrame();
                   
//                    desktop.add(listpdf);
                     listpdf.setVisible(true);
                    break;
                case 18:
                    DocInfoFrame docinfo=new DocInfoFrame();
                    docinfo.setVisible(true);
                    break;
                case 19:
                    showPendingDocument();
                    break;
                case 20:
                    break;
                case 21:
                    break;
                default :
                    new JOptionPane().
                            showMessageDialog(this,Integer.toString(menuID)+":"+
                            Desc);
                     
            }
        }
    public mainFrame(int GroupID) throws HeadlessException {
        super.setTitle("Workflow Management System versi 1.0");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        drawMenuModel(GroupID);
        this.setJMenuBar(menubar);
        this.setSize(800,640);
        desktop=new JDesktopPane();
        this.add(desktop);
        this.setVisible(true);
        
    }
//    public static void main(String args[]) {
//        
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new mainFrame();
//            }
//        });
//        
//        
//    }
    
    
}
